//! # RustCloud 容错与恢复机制
//!
//! 提供企业级的容错和恢复功能，包括死信队列、重试机制、错误处理策略等。
//! 
//! ## 核心功能
//! 
//! - **死信队列**：处理失败消息，支持重试和持久化
//! - **重试机制**：可配置的重试策略，支持多种退避算法
//! - **错误处理**：统一的错误处理框架，支持策略组合
//! - **超时管理**：统一的超时控制和管理
//! - **容错模式**：实现常见的容错设计模式
//! 
//! ## 快速开始
//! 
//! ```rust
//! use rustcloud_resilience::prelude::*;
//! 
//! #[tokio::main]
//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     // 创建重试策略
//!     let retry_strategy = ExponentialBackoffStrategy::new(
//!         std::time::Duration::from_millis(100),
//!         std::time::Duration::from_secs(30),
//!         2.0
//!     );
//!     
//!     // 创建错误处理器
//!     let error_handler = RetryErrorHandler::new(std::sync::Arc::new(retry_strategy));
//!     
//!     Ok(())
//! }
//! ```

pub mod dead_letter;
pub mod retry;
pub mod error_handling;
pub mod timeout;

// 重新导出核心类型和 trait
pub use dead_letter::*;
pub use retry::*;
pub use error_handling::*;
pub use timeout::*;

/// 便利的 prelude 模块，包含常用的类型和 trait
pub mod prelude {
    pub use crate::dead_letter::{
        DeadLetterQueue, DeadLetterConfig, DeadLetterMessage, DeadLetterStats,
        RetryDelayStrategy, AlertThresholds, Alert, AlertLevel
    };
    
    pub use crate::retry::{
        RetryStrategy, BackoffStrategy, RetryConfig, RetryCondition,
        ExponentialBackoffStrategy, LinearBackoffStrategy, FixedDelayStrategy,
        RetryExecutor, RetryResult
    };
    
    pub use crate::error_handling::{
        ErrorHandler, ErrorHandlingStrategy, ErrorHandlingResult,
        RetryErrorHandler, DeadLetterErrorHandler, SkipErrorHandler,
        CompositeErrorHandler, ErrorHandlerFactory
    };
    
    pub use crate::timeout::{
        TimeoutManager, TimeoutConfig, TimeoutStrategy,
        TimeoutResult, TimeoutError
    };
}

/// 重新导出核心错误类型
pub use rustcloud_core::{ServiceError, ServiceResult};

/// 容错机制结果类型
pub type ResilienceResult<T> = Result<T, ResilienceError>;

/// 容错机制错误类型
#[derive(Debug, Clone, thiserror::Error)]
pub enum ResilienceError {
    #[error("死信队列错误: {0}")]
    DeadLetterError(String),
    
    #[error("重试策略错误: {0}")]
    RetryError(String),
    
    #[error("错误处理器错误: {0}")]
    ErrorHandlerError(String),
    
    #[error("超时管理错误: {0}")]
    TimeoutError(String),
    
    #[error("配置错误: {0}")]
    ConfigError(String),
    
    #[error("内部错误: {0}")]
    InternalError(String),
}

impl ResilienceError {
    /// 创建死信队列错误
    pub fn dead_letter_error(msg: impl Into<String>) -> Self {
        Self::DeadLetterError(msg.into())
    }
    
    /// 创建重试错误
    pub fn retry_error(msg: impl Into<String>) -> Self {
        Self::RetryError(msg.into())
    }
    
    /// 创建错误处理器错误
    pub fn error_handler_error(msg: impl Into<String>) -> Self {
        Self::ErrorHandlerError(msg.into())
    }
    
    /// 创建超时错误
    pub fn timeout_error(msg: impl Into<String>) -> Self {
        Self::TimeoutError(msg.into())
    }
    
    /// 创建配置错误
    pub fn config_error(msg: impl Into<String>) -> Self {
        Self::ConfigError(msg.into())
    }
    
    /// 创建内部错误
    pub fn internal_error(msg: impl Into<String>) -> Self {
        Self::InternalError(msg.into())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;
    use std::sync::Arc;

    #[test]
    fn test_resilience_error_creation() {
        let error = ResilienceError::dead_letter_error("test error");
        assert!(matches!(error, ResilienceError::DeadLetterError(_)));
        
        let error = ResilienceError::retry_error("retry failed");
        assert!(matches!(error, ResilienceError::RetryError(_)));
    }

    #[test]
    fn test_retry_strategies() {
        // 测试指数退避策略
        let exponential = ExponentialBackoffStrategy::new(
            Duration::from_millis(100),
            Duration::from_secs(30),
            2.0
        );
        
        assert_eq!(exponential.calculate_delay(0), Duration::from_millis(100));
        assert_eq!(exponential.calculate_delay(1), Duration::from_millis(100));
        assert_eq!(exponential.calculate_delay(2), Duration::from_millis(200));
        
        // 测试线性退避策略
        let linear = LinearBackoffStrategy::new(
            Duration::from_millis(100),
            Duration::from_millis(50)
        );
        
        assert_eq!(linear.calculate_delay(0), Duration::from_millis(100));
        assert_eq!(linear.calculate_delay(1), Duration::from_millis(150));
        assert_eq!(linear.calculate_delay(2), Duration::from_millis(200));
        
        // 测试固定延迟策略
        let fixed = FixedDelayStrategy::new(Duration::from_millis(500));
        
        assert_eq!(fixed.calculate_delay(0), Duration::from_millis(500));
        assert_eq!(fixed.calculate_delay(5), Duration::from_millis(500));
    }

    #[test]
    fn test_backoff_strategy_calculation() {
        use crate::error_handling::BackoffStrategy;
        
        let fixed = BackoffStrategy::Fixed { delay_ms: 1000 };
        assert_eq!(fixed.calculate_delay(0), Duration::from_millis(1000));
        assert_eq!(fixed.calculate_delay(3), Duration::from_millis(1000));
        
        let linear = BackoffStrategy::Linear { 
            initial_delay_ms: 100, 
            increment_ms: 50 
        };
        assert_eq!(linear.calculate_delay(0), Duration::from_millis(100));
        assert_eq!(linear.calculate_delay(2), Duration::from_millis(200));
        
        let exponential = BackoffStrategy::Exponential { 
            initial_delay_ms: 100, 
            max_delay_ms: 5000, 
            multiplier: 2.0 
        };
        assert_eq!(exponential.calculate_delay(0), Duration::from_millis(100));
        assert_eq!(exponential.calculate_delay(3), Duration::from_millis(800));
    }

    #[tokio::test]
    async fn test_error_handlers() {
        // 测试跳过错误处理器
        let skip_handler = SkipErrorHandler::new();
        let context = error_handling::ErrorContext::default();
        let test_error = ResilienceError::internal_error("test");
        
        let result = skip_handler.handle_error(&test_error, &context).await.unwrap();
        assert!(matches!(result, ErrorHandlingResult::Skip));
        
        // 测试重试错误处理器
        let retry_strategy = Arc::new(ExponentialBackoffStrategy::new(
            Duration::from_millis(100),
            Duration::from_secs(30),
            2.0
        ));
        let retry_handler = RetryErrorHandler::new(retry_strategy);
        
        let result = retry_handler.handle_error(&test_error, &context).await.unwrap();
        assert!(matches!(result, ErrorHandlingResult::Retry { .. }));
    }

    #[test]
    fn test_default_configs() {
        let dead_letter_config = DeadLetterConfig::default();
        assert!(dead_letter_config.enabled);
        assert_eq!(dead_letter_config.max_retry_attempts, 3);
        
        let retry_config = RetryConfig::default();
        assert_eq!(retry_config.max_attempts, 3);
        assert!(retry_config.jitter_enabled);
        
        let timeout_config = TimeoutConfig::default();
        assert!(timeout_config.enabled);
        assert_eq!(timeout_config.connect_timeout, Duration::from_secs(30));
    }
}